﻿using DataModels.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace PropertyManagementWebApi.Controllers
{
    [AllowAnonymous]
    [ApiController]
    [Route("api/[controller]/[action]")]
    [ApiExplorerSettings(IgnoreApi = true)]
    public class FilesController(IWebHostEnvironment environment, IConfiguration config) :BaseController
    {
        private readonly IWebHostEnvironment _environment = environment;
        private readonly IConfiguration _config = config;


        [HttpPost]
        [RequestSizeLimit(100_000_000)] // 100MB 限制
        public async Task<ResponseModel> Upload([FromForm] IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return res.Error("没有上传文件");
            }

            try
            {


                // 获取文件扩展名（小写，不含点）
                var fileExtension = Path.GetExtension(file.FileName).TrimStart('.').ToLowerInvariant();

                // 获取当前年月（YYYY-MM）
                var currentMonth = DateTime.Now.ToString("yyyy-MM");

                var baseCode = _config["UploadPath:Path"];


                // 构建分层目录结构：wwwroot/uploads/扩展名/年月
                var uploadsFolder = Path.Combine(
                    baseCode,
                    "applet",
                    "uploads",
                    fileExtension,
                    currentMonth
                );

                // 确保目录存在
                if (!Directory.Exists(uploadsFolder))
                {
                    Directory.CreateDirectory(uploadsFolder);
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid()}.{fileExtension}";
                var filePath = Path.Combine(uploadsFolder, fileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回相对路径（用于前端访问）
                var relativePath = $"/applet/uploads/{fileExtension}/{currentMonth}/{fileName}";
                return res.Success(relativePath);
            }
            catch (Exception ex)
            {
                return res.Error("上传文件失败:" + ex.Message);
            }
        }
    }
}